package com.learn.service;

import com.learn.entity.AdminEntity;
import com.learn.entity.RoleEntity;
import com.learn.repository.AdminRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AdminService implements UserDetailsService {
    @Autowired
    private AdminRepository adminRepository;

    @Autowired
    private RoleService roleService;

    public Page<AdminEntity> getUserList(int page){
        Pageable pageable =   new PageRequest(page, 10, Sort.Direction.DESC, "id");
        return adminRepository.findAll(pageable);
    }

    public AdminEntity findById(int id){
        return adminRepository.findById(id);
    }

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {

        AdminEntity adminEntity =   adminRepository.findByName(userName);
        if(adminEntity == null){
            throw new UsernameNotFoundException("用户名不存在");
        }

        List<RoleEntity> roleEntityList = roleService.roleEntityList(adminEntity.getRoleId());
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for(RoleEntity role:roleEntityList)
        {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        return new User(adminEntity.getName(), adminEntity.getPassword(), authorities);
    }
}
